package cn.smbms.contorller.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFormat.Encoding;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.ACT;
import cn.smbms.tools.Constants;
import cn.smbms.tools.EncodingTool;
import cn.smbms.tools.PageSupport;


@Controller
@RequestMapping("/home")
public class UserController extends BaseConverter{
	private static Logger logger=Logger.getLogger(UserController.class);
	
	/*
	 * 用户业务实现类属性对象
	 */
	@Resource(name="userServiceImpl")
	private UserServiceImpl userService;
	
	/*
	 * 角色业务实现类属性对象
	 */
	@Resource(name="roleServiceImpl")
	private RoleService roleService;
	
	
	
	/*用户方法功能判断*/
	@RequestMapping(value="/entrance",method=RequestMethod.GET)
	public String entrance(
			@RequestParam(value="method",required=true)String method,
			HttpServletRequest request, HttpServletResponse response){
		
		if(method != null && method.equals("query")){
			/*this.query(request, response);*/
			logger.debug("=====================query");
			return "redirect:/home/query";
		}
		return "";
	}
	
	
	/*查询用户列表*/
	@RequestMapping(value="/query",method=RequestMethod.GET)
	public String query(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="queryname",required=false)String queryname1,
			@RequestParam(value="queryUserRole",required=false)String queryUserRole1,
			@RequestParam(value="pageIndex",required=false)String pageIndex1
			)
			throws ServletException, IOException {
		//查询用户列表
		String queryUserName = queryname1;
		String temp = queryUserRole1;
		String pageIndex = pageIndex1;
		int queryUserRole = 0;
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
		/**
		 * http://localhost:8090/SMBMS/userlist.do
		 * ----queryUserName --NULL
		 * http://localhost:8090/SMBMS/userlist.do?queryname=
		 * --queryUserName ---""
		 */
		System.out.println("queryUserName servlet--------"+queryUserName);  
		System.out.println("queryUserRole servlet--------"+queryUserRole);  
		System.out.println("query pageIndex--------- > " + pageIndex);
		if(queryUserName == null){
			queryUserName = "";
		}
		if(temp != null && !temp.equals("")){
			queryUserRole = Integer.parseInt(temp);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			response.sendRedirect("error.jsp");
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	
    	int totalPageCount = pages.getTotalPageCount();
    	
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		
		
		userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize);
		request.setAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		request.setAttribute("roleList", roleList);
		request.setAttribute("queryUserName", queryUserName);
		request.setAttribute("queryUserRole", queryUserRole);
		request.setAttribute("totalPageCount", totalPageCount);
		request.setAttribute("totalCount", totalCount);
		request.setAttribute("currentPageNo", currentPageNo);
		/*request.getRequestDispatcher("userlist.jsp").forward(request, response);*/
		return "userlist";
	}
	
	
	/*用户信息查看*/
	@RequestMapping(value="/views")
	public String getUserById(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="uid",required=true)String userid)
			throws ServletException, IOException {
		String id = userid;
		if(!StringUtils.isNullOrEmpty(id)){
			System.out.println("进入查看用户信息");
			//调用后台方法得到user对象
			User user = userService.getUserById(id);
			request.setAttribute("user", user);
		}
		return "userview";
	}
	
	
	/*用户编辑信息*/
	@RequestMapping(value="/modiy")
	public String userModiy(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="uid",required=true)String userid)
			throws ServletException, IOException {
		String id = userid;
		if(!StringUtils.isNullOrEmpty(id)){
			System.out.println("进入查看用户信息");
			//调用后台方法得到user对象
			User user = userService.getUserById(id);
			request.setAttribute("user", user);
			
		}
		return "usermodify";
	}
	
	
	/*在用户编辑信息里获取可选择用户角色produces = "application/json; charset=utf-8"*/
	@RequestMapping(value="/getRoleList",method=RequestMethod.GET)
	@ResponseBody
	public String getRoleList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		/*//把roleList转换成json对象输出
		response.setContentType("application/json");*/
		String rols=JSONArray.toJSONString(roleList);
		return rols;
	}
	
	
	/*
	 * 用户修改信息方法
	 */
	@RequestMapping(value="/userModiy",method=RequestMethod.POST)
	private String modify(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("uid")String uid1,
			@RequestParam("userName")String userName1,
			@RequestParam("gender")String gender1,
			@RequestParam("birthday")String birthday1,
			@RequestParam("phone")String phone1,
			@RequestParam("address")String address1,
			@RequestParam("userRole")String userRole1
			)
			throws ServletException, IOException {
		String id = uid1;
		String userName = userName1 ;
		String gender = gender1;
		String birthday = birthday1;
		String phone = phone1;
		String address = address1;
		String userRole = userRole1;
		
		User user = new User();
		user.setId(Integer.valueOf(id));
		user.setUserName(userName);
		user.setGender(Integer.valueOf(gender));
		try {
			user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
			Date de=user.getBirthday();
			Date da=new java.sql.Date(de.getTime());
			user.setBirthday(da);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user.setPhone(phone);
		user.setAddress(address);
		user.setUserRole(Integer.valueOf(userRole));
		user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		Date da1=user.getModifyDate();
		Date ds=new java.sql.Date(da1.getTime());
		user.setModifyDate(ds);
		if(userService.modify(user)){
			logger.debug("修改成功！");
			return "redirect:/home/query";
		
		}else{
			logger.debug("修改失败！");
			return "usermodify";
			
			
		}
	
	}
	
	
	/*
	 * 删除用户方法
	 */
	@RequestMapping(value="/delUser",method=RequestMethod.GET)
	@ResponseBody
	private String delUser(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("uid")String userRole1)
			throws ServletException, IOException {
		String id = EncodingTool.encodeStr(userRole1);
		Integer delId = 0;
		try{
			delId = Integer.parseInt(id);
		}catch (Exception e) {
			// TODO: handle exception
			delId = 0;
		}
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(delId <= 0){
			resultMap.put("delResult", "notexist");
		}else{
			if(userService.deleteUserById(delId)){
				System.out.println("删除成功！");
				resultMap.put("delResult", "true");
			}else{
				resultMap.put("delResult", "false");
			}
		}
		
	String json=JSONObject.toJSONString(resultMap);
	System.out.println(json);
		return json;
	}
	
	
	
	/*
	 * 用户添加保存
	 */
	@RequestMapping(value="/userAdd",method=RequestMethod.POST)
	public String add(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="userCode")String userCode1,
			@RequestParam(value="userName")String userName1,
			@RequestParam(value="userPassword")String userPassword1,
			@RequestParam(value="gender")String gender1,
			@RequestParam(value="birthday")String birthday1,
			@RequestParam(value="phone")String phone1,
			@RequestParam(value="address")String address1,
			@RequestParam(value="userRole")String userRole1
			)
			throws ServletException, IOException {
		System.out.println("add()================");
		String userCode =userCode1;
		String userName =userName1;
		String userPassword = userPassword1;
		String gender = gender1;
		String birthday = birthday1;
		String phone = phone1;
		String address = address1;
		String userRole = userRole1;
		User user = new User();
		user.setUserCode(userCode);
		user.setUserName(userName);
		user.setUserPassword(userPassword);
		user.setAddress(address);
		
			String time = birthday;
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
		    Date utilDate;
			try {
				utilDate = sdf.parse(time);
				System.out.println(utilDate);//查看utilDate的值
			    Date date = new java.sql.Date(utilDate.getTime());
			    System.out.println(date);//查看date的值
			    user.setBirthday(date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
		user.setGender(Integer.valueOf(gender));
		user.setPhone(phone);
		user.setUserRole(Integer.valueOf(userRole));
	
		user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
		
		if(userService.add(user)){
			return "redirect:/home/query";
		}else{
			return "useradd";
		}
	}
	
	/*
	 * 用户编码判断
	 */
	@RequestMapping(value="/userAdd",method=RequestMethod.GET)
	@ResponseBody
	public String userCodeExist(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="userCode")String userCode1
			)
			throws ServletException, IOException {
		//判断用户账号是否可用
		String userCode = userCode1;
		
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(StringUtils.isNullOrEmpty(userCode)){
			//userCode == null || userCode.equals("")
			resultMap.put("userCode", "exist");
		}else{
			User user = userService.selectUserCodeExist(userCode);
			if(null != user){
				resultMap.put("userCode","exist");
			}else{
				resultMap.put("userCode", "notexist");
			}
		}
		
		String json=JSONObject.toJSONString(resultMap);
		System.out.println(json);
			return json;
	}
	
	
	/*
	 * 用户修改密码验证
	 */
	@RequestMapping(value="/updPass",method=RequestMethod.GET)
	@ResponseBody
	public String getPwdByUserId(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value="oldpassword")String oldpassword1)
			throws ServletException, IOException {
		Object o = request.getSession().getAttribute(Constants.USER_SESSION);
		String oldpassword = oldpassword1;
		Map<String, String> resultMap = new HashMap<String, String>();
		
		if(null == o ){//session过期
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
			resultMap.put("result", "error");
		}else{
			String sessionPwd = ((User)o).getUserPassword();
			if(oldpassword.equals(sessionPwd)){
				resultMap.put("result", "true");
			}else{//旧密码输入不正确
				resultMap.put("result", "false");
			}
		}
		
		String json=JSONObject.toJSONString(resultMap);
		System.out.println(json);
			return json;
	}
	
	/*
	 * 保存用户修改的密码
	 */
	@RequestMapping(value="/submitPass",method=RequestMethod.POST)
	public String updatePwd(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value="newpassword")String newpassword1)
			throws ServletException, IOException {
		
		Object o = request.getSession().getAttribute(Constants.USER_SESSION);
		String newpassword = newpassword1;
		boolean flag = false;
		if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
			flag = userService.updatePwd(((User)o).getId(),newpassword);
			if(flag){
				request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
				request.getSession().removeAttribute(Constants.USER_SESSION);//session注销
			}else{
				request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
			}
		}else{
			request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
		}
		return "pwdmodify";
	}
	
	
	
	
}
